package com.example.smartwaterapi.controller;

import com.example.smartwaterapi.common.api.ApiResponse;
import com.example.smartwaterapi.service.WeatherService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.HashMap;

@Slf4j
@Tag(name = "天气API", description = "天气相关接口")
@RestController
@RequestMapping("/api/weather")
public class WeatherController {

    @Autowired
    private WeatherService weatherService;

    /**
     * 获取当前天气
     * @return 天气信息
     */
    @Operation(summary = "获取当前天气", description = "根据IP或默认位置获取天气信息")
    @GetMapping("/current")
    public ApiResponse<Map<String, Object>> getCurrentWeather() {
        try {
            Map<String, Object> weatherData = weatherService.getCurrentWeather();
            return ApiResponse.success("获取天气信息成功", weatherData);
        } catch (Exception e) {
            log.error("获取天气信息失败", e);
            return ApiResponse.error("获取天气信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据经纬度获取天气
     * @param latitude 纬度
     * @param longitude 经度
     * @return 天气信息
     */
    @Operation(summary = "根据位置获取天气", description = "通过经纬度获取对应位置的天气信息")
    @GetMapping("/location")
    public ApiResponse<Map<String, Object>> getWeatherByLocation(
            @RequestParam(required = false) Double latitude,
            @RequestParam(required = false) Double longitude) {
        try {
            // 记录请求日志
            log.info("接收到位置天气请求: 纬度={}, 经度={}", latitude, longitude);
            
            // 检查参数
            if (latitude == null || longitude == null) {
                log.warn("位置参数为空，使用默认天气");
                return getCurrentWeather();
            }
            
            // 使用经纬度获取天气
            Map<String, Object> weatherData = weatherService.getWeatherByLocation(latitude, longitude);
            return ApiResponse.success("获取位置天气信息成功", weatherData);
        } catch (Exception e) {
            log.error("获取位置天气信息失败", e);
            return ApiResponse.error("获取天气信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据城市获取天气
     * @param city 城市名称
     * @return 天气信息
     */
    @Operation(summary = "根据城市获取天气", description = "通过指定城市名称获取对应天气信息")
    @GetMapping("/city/{city}")
    public ApiResponse<Map<String, Object>> getWeatherByCity(@PathVariable String city) {
        try {
            Map<String, Object> weatherData = weatherService.getWeatherByCity(city);
            return ApiResponse.success("获取" + city + "天气信息成功", weatherData);
        } catch (Exception e) {
            log.error("获取天气信息失败", e);
            return ApiResponse.error("获取天气信息失败: " + e.getMessage());
        }
    }
} 